import React, { useEffect, useState, useMemo, useContext } from 'react';
import SwitchCell from '../../UIComponent/SwitchCell.jsx';
import Modal from '../../UIComponent/Modal.jsx';
import Input from '../../UIComponent/Input.jsx';
import Checkbox from '../../UIComponent/Checkbox.jsx';
import Loading from '../../UIComponent/Loading.jsx';
import LoadingToast from '../../UIComponent/LoadingToast.jsx';
import styles from './PersonnelSetting.scss';
import _ from 'lodash';
import {
    fetchUserList,
    fetchOriginList,
    fetchSyncDataUser,
    fetchSyncDataOrigin,
    fetchRoleList,
    getUserConfigList,
} from './api';
import AppContext from '../../context';
import mock from './mock';

export default function PersonnelSetting() {
    const [data, setData] = useState([]);
    const [selectedItem, setSelectItem] = useState([{ org_name: '全部', id: '', parent_id: '', path: [0], disable: true, _index: 0 }]);
    const [userList, setUserList] = useState([]);
    const [currentUser, setCurrentUser] = useState([]);
    const [departmentIds, setDepartmentIds] = useState([]);
    const [roleList, setRoleList] = useState([]);
    const [visible, setVisible] = useState(false);
    const [checkedRoleName, setCheckedRoleName] = useState([]); // 当前人员选中的角色
    const [currentOrgId, setCurrentOrgId] = useState(''); // 当前选中的组织id(用于显示员工）
    const [path, setPath] = useState([0]);
    const [isLoading, setLoading] = useState(false);
    const app = useContext(AppContext);
    useEffect(() => {
            onGetUsrList()
            .then(result => {
                return onGetOriginList(result.data, Object.keys(result.data))
            })
            .then(() => getUserConfigList())
            .then(result => {
                const ids = result.data.map(item => item.org_id);
                setDepartmentIds(ids);
                return fetchRoleList(app.user.company_id, 1, 20)
            }).then(result => {
                setRoleList(result.data);
            })
    }, []);
    // 生成该组织下的所有子级组织
    function findItemsChild(org) {
        const _child = org.child.map(c => {
            const child_id = [];
            const recursion = (obj) => {
                obj.child.map(children => {
                    if (_.get(children, ['child', 'length']) && _.get(children, ['child', 'length']) > 0) {
                        recursion(children);
                    }
                    child_id.push(children.id);
                });
                return child_id;
            };
            return { ...c, child_id: recursion(c) };
        });
        return _child;
    }
    // 查找该组织下的员工数量
    function findOrgMemberTotal(list, _userList = userList, _ids = departmentIds) {
        const _list = list.map(item => {
            let total = _.get(_userList, [item.id, 'length']) || 0;
            _.get(item, ['child_id']) && _.get(item, ['child_id']).map(id => {
                const len = _.get(_userList, [id, 'length']) || 0;
                total += len;
            });
            item.total = total;
            item.checked = _ids.includes(item.id);
            return item;
        });
        return _list;
    }
    function onGetOriginList(_userList, ids) {
        return fetchOriginList()
            .then(result => {
                setData(result.data);
                return result.data;
            })
    }
    function onGetUsrList() {
        return fetchUserList().then(result => {
            setUserList(result.data);
            return result;
        });
    }
    function onclickSub(item, index) {
        const children = _.get(item, ['child']);
        const _selectedItem = _.clone(selectedItem);
        _.unset(_selectedItem, [_selectedItem.length - 1, 'disable']);
        if (children && children.length > 0) {
            setPath([...path, 'child', index]);
            setSelectItem([..._selectedItem, { org_name: item.org_name, id: item.id, parent_id: item.parent_id, index, _index: _selectedItem.length, path: [...path, 'child', index], disable: true }]);
        } else {
            const user = _.get(userList, [item.id]);
            if (user) {
                setCurrentOrgId(item.id);
                setSelectItem([...selectedItem, { org_name: item.org_name, id: item.id, parent_id: item.parent_id, index, path: [...path, 'child', index], _index: selectedItem.length, disable: true }]);
            }
        }
    }
    function onChecked(item, index, e) {
        e.stopPropagation();
        const _ids = _.cloneDeep(departmentIds);
        const isCheck = departmentIds.includes(item.id);
        if (!isCheck) {
            setDepartmentIds([..._ids, item.id]);
        } else {
            _.remove(_ids, id => id === item.id);
            setDepartmentIds(_ids);
        }
    }
    // 寻找组织
    function onFindOrigin(item, index) {
        if (_.get(item, ['disable'])) return;
        const _selectedItem = selectedItem.filter(it => {
            return it._index <= index;
        });
        _.set(_selectedItem, [_selectedItem.length - 1, 'disable'], true);
        setPath(item.path);
        setCurrentOrgId('');
        setSelectItem(_selectedItem);
    }
    function onSyncOrigin() {
        setLoading(true);
        fetchSyncDataOrigin().then(() => {
            setSelectItem([{ org_name: '全部', id: '', parent_id: '' }]);
            setLoading(false);
            onGetOriginList();
        }).catch(() => {
            setLoading(false);
        });
    }
    function onSyncUser() {
        setLoading(true);
        fetchSyncDataUser({ department_ids: departmentIds.join(','), company_id: app.user.company_id }).then(() => {
            setLoading(false);
            return onGetUsrList();
        }).then(user_list => {
            setUserList(user_list.data);
        }).catch(() => {
            setLoading(false);
        });
    }
    function onEditUser(user) {
        if (Array.isArray(user.roles)) {
            setCheckedRoleName(user.roles);
        }
        setVisible(true);
        setCurrentUser(user);
    }
    function onChangeRole(role) {
        if (checkedRoleName.includes(role.role_name)) {
            const _checkedRoleName = _.cloneDeep(checkedRoleName);
            _.remove(_checkedRoleName, name => name === role.role_name);
            setCheckedRoleName(_checkedRoleName);
        } else {
            setCheckedRoleName([...checkedRoleName, role.role_name]);
        }
    }
    function onSetUpRole() {
        setCheckedRoleName([]);
        onGetUsrList();
        setVisible(false);
    }
    function onCancelSetUpRole() {
        setCheckedRoleName([]);
        setVisible(false);
    }
    const renderText = useMemo(() => {
        const total = selectedItem.length;
        return (
            <div className={styles.bread_crumb}>
                {selectedItem && selectedItem.map((item) => (
                    <span key={item._index + 1} onClick={() => onFindOrigin(item, item._index)}>
                        <span className={styles.department_name}
                              style={{color: _.get(item, ['disable']) ? '#847f7f' : ''}}>{item.org_name}</span>
                        {item._index < total - 1 && <i className='iconfont icon_arrow'/>}
                    </span>)
                )}
            </div>
        )
    }, [selectedItem, userList]);
    const renderDepartment = useMemo(() => {
        if (!_.get(data, [...path])) return <Loading />;
        const list = findOrgMemberTotal(findItemsChild(_.get(data, [...path])));
        const parent_id = _.get(list, [0, 'parent_id']);
        const parentUser = list.length > 0 && _.get(userList, [parent_id]);
        return (
            <div>
                {list && list.map((item, index) => {
                    return (
                        <SwitchCell
                            key={item.id}
                            label={
                                <div className={styles.origin_cell}>
                                    <div className={styles.origin_head}><i className='iconfont icon_organization' /></div>
                                    <span className={item.total ? `${styles.selected}` : ''}>{item.org_name}({item.total || 0}人)</span>
                                </div>
                            }
                            onClick={() => onclickSub(item, index)}
                            onChange={(e) => onChecked(item, index, e)}
                            checked={item.checked}
                        />
                    );
                })}
                {parentUser && parentUser.map(user =>
                    <div className={styles.user_info} key={user.job_number} onClick={() => onEditUser(user)}>
                        <div className={styles.user_head}>{user.user_name.substring(1, 3)}</div>
                        <div className={styles.tag_box}>
                            <div>{user.user_name}</div>
                            <div>
                                <div className={styles.tag}>
                                    {Array.isArray(user.roles) && user.roles.map((role, index) => <span key={`role${index}`} className={styles.role}>{role}</span>)}
                                    <span className={styles.role}>{user.position}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
                {list.length === 0 && <Loading />}
            </div>);
    }, [departmentIds, userList, data, path]);
    // 渲染成员
    function renderMember() {
        return (
            <div>
                {_.get(userList, [currentOrgId]) && _.get(userList, [currentOrgId]).map(user =>
                    <div className={styles.user_info} key={user.id} onClick={() => onEditUser(user)}>
                        <div className={styles.user_head}>{user.user_name.substring(1, 3)}</div>
                        <div className={styles.tag_box}>
                            <div>{user.user_name}</div>
                            <div>
                                <div className={styles.tag}>
                                    {Array.isArray(user.roles) && user.roles.map((role, index) => <span key={index + 1} className={styles.role}>{role}</span>)}
                                    <span className={styles.role}>{user.position}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
                {!_.get(userList, [currentOrgId]) && <Loading />}
            </div>
        )
    }
    return (
        <div className={styles.container}>
            {isLoading && <LoadingToast />}
            <div className={styles.content}>
                {renderText}
                <div className={styles.list}>{!currentOrgId ? renderDepartment : renderMember()}</div>
            </div>
            {visible && <Modal
                title='人员编辑'
                visible={visible}
                onOk={() => onSetUpRole()}
                onCancel={() => onCancelSetUpRole()}
            >
                <Input label='姓名' value={currentUser.user_name} disabled />
                <div className={styles.set_role}>角色设置</div>
                {roleList.map((role, index) => <Checkbox key={index + 1} label={role.role_name} checked={checkedRoleName.includes(role.role_name)} onClick={() => onChangeRole(role)} />)}
            </Modal>}
        </div>
    );
}
